﻿using System;
using System.IO;
using System.Text;
using Microsoft.Extensions.Logging;

namespace Micro.Extensions.Bridge
{
    public static class RegistrationUtility
    {
        /// <summary>
        /// 获取注册ID 同一位置部署，注册ID应该保持一致
        /// </summary>
        /// <returns></returns>
        public static string RegistrationId(ILogger logger)
        {
            try
            {
                var basePath = Directory.GetCurrentDirectory();
                var folderPath = Path.Combine(basePath, "registrationid");
                if (!Directory.Exists(folderPath))
                    Directory.CreateDirectory(folderPath);

                var path = Path.Combine(basePath, "registrationid", ".id");
                if (File.Exists(path))
                {
                    var lines = File.ReadAllLines(path, Encoding.UTF8);
                    if (lines.Length > 0 && !string.IsNullOrEmpty(lines[0]))
                        return lines[0];
                }

                var id = Guid.NewGuid().ToString();
                File.AppendAllLines(path, new[] { id });
                return id;
            }
            catch (Exception e)
            {
                logger.LogBridge(LogLevel.Error, "获取 Registration Id 错误", e);
                return Guid.NewGuid().ToString();
            }
        }
    }
}
